package com.zhen.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.text.StringEscapeUtils;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class HTMLSpirit {

	public static String[] CHECK_STR;
	private final Logger log = LoggerFactory.getLogger(HTMLSpirit.class);
	static {
		ResourceBundle bundle = ResourceBundle.getBundle("config/check");
		String str = bundle.getString("html.checked.str");
		if (!StringUtils.isEmpty(str)) {
			CHECK_STR = str.split(",");
		}
	}
	private String url;
	private Response execute;
	
	public HTMLSpirit(String url) throws IOException, KeyManagementException, NoSuchAlgorithmException {
		
		this.url = url;
		System.out.println(url);
		try {
//			System.setProperty("javax.net.debug","ssl");
			System.setProperty("https.protocols", "TLSv1.2"); 
			trustEveryone();
			execute = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
				    .execute();
//			System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
//			Connection conn = HttpConnection.connect(url);
//			conn.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//			conn.header("Accept-Encoding", "gzip, deflate, br");
//			conn.header("Accept-Language", "zh-CN,zh;q=0.9");
//			conn.header("Cache-Control", "max-age=0");
//			conn.header("Connection", "keep-alive");
//			conn.header("Host", "blog.maxleap.cn");
//			conn.header("Upgrade-Insecure-Requests", "1");
//			conn.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36");
//			execute = conn.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
//				    .execute();
		} catch (SSLHandshakeException e) {
			/*disableSSLCertCheck();
			System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
			execute = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
				    .execute();*/
			e.printStackTrace();
		}
	}

	public int getStatus() throws IOException{
		
		return execute.statusCode();
	}
	public String getHtml() throws IOException{
		return execute.parse().toString();
		
	}
	public  String delHTMLTag(String htmlStr) {
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签
//		htmlStr = StringEscapeUtils.unescapeHtml4(htmlStr);
		return MyStringUtils.replaceBlank(htmlStr); // 返回文本字符串
	}

	public  String getHtmlStr(String url) throws MalformedURLException, IOException {
		return getHtmlStr(url, 1000);
	}

	public  String getHtmlStr(String url, Integer connectTimeout) throws MalformedURLException, IOException {
		Document doc = null;
		String str = "";
		try {
			disableSSLCertCheck();
		} catch (KeyManagementException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		Connection connect = Jsoup.connect(url);
		doc = connect.get();
		// doc = Jsoup.parse(new URL(url),5000);
		if (doc != null) {

			str = delHTMLTag(doc.toString());
		}
		return str;
	}

	public static void main(String[] args) {
		Document doc = null;
		/*try {
			disableSSLCertCheck();
		} catch (KeyManagementException | NoSuchAlgorithmException e) {
			e.printStackTrace();
		}*/
		try {

			// doc = Jsoup.parse(new
			// URL("https://member.chimebank.com/join/muyang"),5000);
			try {
//				System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
//				System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
				System.setProperty("javax.net.debug","ssl");
				System.setProperty("https.protocols", "TLSv1"); 
				disableSSLCertCheck();
			} catch (KeyManagementException | NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			}
			 Response execute = Jsoup.connect("https://www.referyourchasecard.com/252/WBQCEGPC69").userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
				    .execute();
//			 Response execute = Jsoup.connect("http://share.robinhood.com/yangy50").userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
//					 .execute();
			 System.out.println(execute.statusCode());
			 doc = execute.parse();
			 System.out.println(doc.toString());
		} catch (SSLHandshakeException e) {
			/*System.out.println("进来了");
			try {
				disableSSLCertCheck();
			} catch (KeyManagementException | NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			}
			Response execute = null;
			try {
				execute = Jsoup.connect("http://www.swagbucks.com/p/register?rb=21955932").userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
					    .execute();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			 System.out.println(execute.statusCode());*/
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
//		String delHTMLTag = delHTMLTag(doc.toString());
//		System.out.println(delHTMLTag);
//		System.out.println(delHTMLTag.indexOf("GetDoubleCashBackonSpringSavings"));

	private static  void disableSSLCertCheck() throws NoSuchAlgorithmException, KeyManagementException {
		// Create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(X509Certificate[] certs, String authType) {
			}

			public void checkServerTrusted(X509Certificate[] certs, String authType) {
			}
		} };

		// Install the all-trusting trust manager
		/*SSLContext sc = SSLContext.getInstance("TLS");
		System.setProperty("https.protocols", "TLSv1");
//		System.setProperty("https.protocols", "TLSv1.2,TLSv1.1,SSLv3");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());*/

		// Create all-trusting host name verifier
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};

		// Install the all-trusting host verifier
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	}
	/**
	 * 信任任何站点，实现https页面的正常访问
	 * 
	 */
	
	public static void trustEveryone() {
        try {  
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;  
                }
            });  
  
            SSLContext context = SSLContext.getInstance("TLS");  
            context.init(null, new X509TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
  
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }
  
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];  
                }
            } }, new SecureRandom());  
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            // e.printStackTrace();  
        }
    } 


	
}